package com.cloud.sky.controller;

import com.cloud.sky.entity.common.Result;
import com.cloud.sky.entity.common.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

/**
 * @author Tyrone
 * @date 2024/8/6 23:23
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 异常拦截
    @ExceptionHandler(Exception.class)
    public Result ExceptionHandler(Exception e) {

        if (e instanceof MethodArgumentNotValidException) { // 如果是注解拦截的异常 绑定异常
            MethodArgumentNotValidException e1 = (MethodArgumentNotValidException) e;
            StringBuilder builder = new StringBuilder();
            for (ObjectError allError : e1.getAllErrors()) {
                if (allError instanceof FieldError) {
                    FieldError fieldError = (FieldError) allError;
                    builder.append(fieldError.getField()).append("").append(fieldError.getDefaultMessage()).append(";");
                }
            }
            return Result.failure("参数检验异常:" + (StringUtils.isEmpty(builder) ? e1.getMessage() : builder)); //显示 具体错误信息
        }
        return Result.failure(ResultCode.failure);
    }
}
